package com.xx.doublexchat.common.websocket;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.xx.doublexchat.common.websocket.domain.enums.WSReqTypeEnum;
import com.xx.doublexchat.common.websocket.domain.vo.req.WSBaseRequire;
import com.xx.doublexchat.common.websocket.service.WebSocketService;
import com.xx.doublexchat.common.websocket.utils.NettyUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;

import java.util.Objects;

@Slf4j
@ChannelHandler.Sharable
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private WebSocketService webSocketService;

    private WxMpService wxMpService;

    /**
     * 建立通道连接
     *
     * @author 牛顿莱布尼兹欧拉泰勒漩
     * @version 1.0
     * @date 13:56
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 从Spring容器中获取webSocketService
        webSocketService = SpringUtil.getBean(WebSocketService.class);
        webSocketService.connect(ctx.channel());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 监听WebSocketServerProtocolHandler.HandshakeComplete
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            String token = NettyUtils.getAttr(ctx.channel(), NettyUtils.TOKEN);
            if (Objects.nonNull(token)) {
                webSocketService.authorize(ctx.channel(),token);
            }
        } else if (evt instanceof IdleStateEvent) { // 心跳事件类
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) { // 读空闲
                System.out.println("读空闲");
                // 用户下线
                userOffLine(ctx.channel());
            }
        }
    }

    /**
     * 用户下线
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        userOffLine(ctx.channel());
    }

    /**
     * 主动让用户下线方法
     *
     * @param channel --- 通道
     */
    private void userOffLine(Channel channel) {
        webSocketService.remove(channel);
        channel.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        wxMpService = SpringUtil.getBean(WxMpService.class);
        String text = msg.text();
        WSBaseRequire wsBaseRequire = JSONUtil.toBean(text, WSBaseRequire.class);
        switch (WSReqTypeEnum.of(wsBaseRequire.getType())) {
            case AUTHORIZE: // 登录认证
                webSocketService.authorize(ctx.channel(),wsBaseRequire.getData());
                break;
            case HEARTBEAT: // 心跳包---检测用户是否掉线
                break;
            case LOGIN:// 请求登录二维码
                webSocketService.handleLoginReq(ctx.channel(), wxMpService);
                break;
            default:
                break;
        }
    }
}
